package com.xysq.activity;
/**
 * Copyright (c) 2015 XiaoYuanShenQi. All rights reserved.
 
 * Author: Steward_Han
 * Date: 2015-6-23
 * Description: GO to a html5 url
 
*/

import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.xysq.lemon.R;
import com.xysq.util.PropertiesUtil;
import com.xysq.util.UserInfoKeeper;

import java.util.HashMap;
import java.util.Map;

import butterknife.InjectView;

public class WebViewActivity extends BaseActivity implements View.OnClickListener{

	public static String URL = "";
	public static String param = "";
//	private WebView webView;
	private SoundPool soundPool;
	HashMap<Integer, Integer> soundMap = new HashMap<>();
	@InjectView(R.id.webview_details)
	WebView detailsWebView;
	@InjectView(R.id.webview_details)
	WebView webView;
	@InjectView(R.id.ibtn_back)
	ImageButton backIbtn;
    @InjectView(R.id.txt_webview_title)
    TextView webviewTitleTxt;

	public static final String VIEW_COUPON = PropertiesUtil.getH5Address() + "viewCoupon.html";
	public static final String SHARE_SOUND = PropertiesUtil.getH5Address() + "sharingSound.html";
	public static final String SHARE_SOUND_SUCCESS = PropertiesUtil.getH5Address() + "shareSuccessSound.html";
	public static final String SHOP = PropertiesUtil.getH5Address() + "shop.html";//第一个
	public static final String SHAKE = PropertiesUtil.getH5Address() + "shake.html";//第二个
	public static final String FUN = PropertiesUtil.getH5Address() + "fun.html";//第三个
	public static final String TASTE = PropertiesUtil.getH5Address() + "taste.html";//第四个
	public static final String SUCCESS = PropertiesUtil.getH5Address() + "success.html";
	public static final String NAV = PropertiesUtil.getH5Address() + "nav.html";
	public static final String GIFT = PropertiesUtil.getH5Address() + "giftIndex.html";
	public static final String VIEW_COUPON_MODEL = PropertiesUtil.getH5Address() + "viewCouponModel.html";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_webview);
		getExtra();
		initView();
		initWebView();
	}

	private void initView() {
		backIbtn.setOnClickListener(this);
		soundPool= new SoundPool(10, AudioManager.STREAM_SYSTEM,5);
		soundMap.put(1, soundPool.load(WebViewActivity.this, R.raw.shaking, 1));
		soundMap.put(2, soundPool.load(WebViewActivity.this, R.raw.win, 1));
		param = "customerId=" + UserInfoKeeper.readCustomerId(WebViewActivity.this) + "&loginName=" + UserInfoKeeper.readPhoneNumber(this) + "&appKey=" + PropertiesUtil.getAppKey();
		Log.e("+++param", param);
	}

	private void getExtra() {
		Intent intent = getIntent();
		URL = intent.getStringExtra("h5Url");
	}

	private void initWebView() {
		detailsWebView.getSettings().setJavaScriptEnabled(true);
		detailsWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        //加载需要显示的网页
		detailsWebView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.e("my Url", url);
				String baseUrl = processUrl(url);
				if (baseUrl.equals(VIEW_COUPON)) {
					startActivity(new Intent(WebViewActivity.this, MyTicketsActivity.class));
				} else if (baseUrl.equals(SHARE_SOUND)) {
					Log.e("+++摇一摇", "现在是摇一摇");
					soundPool.play(soundMap.get(1), 1, 1, 1, 0, 1);

				} else if (baseUrl.equals(SHARE_SOUND_SUCCESS)) {
					Log.e("+++摇中了", "现在是摇中了");
					soundPool.play(soundMap.get(2), 1, 1, 0, 0, 1);
				} else if (baseUrl.equals(VIEW_COUPON_MODEL)) {
					Log.e("+++现在要跳到券详情", "跳到券详情");
					Intent intent = new Intent(WebViewActivity.this, CommodityDetailsActivity.class);
					HashMap<String, String> params = new HashMap<>();
					processUrl(url, params);
					String couponModelId = params.get("couponModelId");
					int intCouponModelId;
					try {
						intCouponModelId = Integer.valueOf(couponModelId);
					}catch (Exception e){
						Log.e("couponModelId 格式错误", couponModelId);
						return true;
					}
					intent.putExtra(CommodityDetailsActivity.COUPONMODEL_ID, intCouponModelId);
					intent.putExtra(CommodityDetailsActivity.TYPE, "type");
					Log.e("++++++couponModelId", intCouponModelId + "");
					startActivity(intent);

				} else {
					view.loadUrl(url);
				}
				return true;
			}
		});

		analyze(URL);

		//设置Web视图
//        setContentView(detailsWebView);
    }

	private void analyze(String url) {
		Log.e("Url", url);
		if(url.equals(SHAKE)) {
			Log.e("Url", getRelativeUrl(url));
			if (TextUtils.isEmpty(UserInfoKeeper.readPhoneNumber(this))) {
				startActivity(new Intent(this, LoginActivity.class));
				finish();
			}else {
				detailsWebView.loadUrl(getRelativeUrl(url));
				webviewTitleTxt.setText("白送");
			}
		}else if(url.equals(GIFT)) {
			Log.e("Url", getRelativeUrl(url));
			detailsWebView.loadUrl(getRelativeUrl(url));
            webviewTitleTxt.setText("新生大礼包");
		}else {
			detailsWebView.loadUrl(url);
            webviewTitleTxt.setText("");
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		detailsWebView.destroy();
	}

	public String getRelativeUrl(String url){
		return url + "?" + param;
	}

	private static String processUrl(String url) {
		String picUrl[] = splitUrl(url);
		return  picUrl[0];
	}

	private static String processUrl(String url, Map<String, String> params) {
		String picUrl[] = splitUrl(url);
		String baseUrl = picUrl[0];
		String paramString = picUrl[1];
		splitParams(paramString, params);
		return  baseUrl;
	}

	private static void splitParams(String paramString, Map<String, String> params) {
		String divider = "&";
		String[] separateParam = paramString.split(divider);

		for(int i = 0;i<separateParam.length;i++){
			splitSingleParam(separateParam[i], params);
		}
	}

	private static void splitSingleParam(String singleParam, Map<String, String> params) {
		String divider = "=";
		String[] mapParam = singleParam.split(divider);
		params.put(mapParam[0], mapParam[1]);
	}

	private static String[] splitUrl(String picUrls) {
		String divider = "\\?";
		String[] picUrl = picUrls.split(divider);
		return picUrl;
	}

	@Override
	public void onClick(View view) {
		if(view == backIbtn){
            finish();
		}
	}

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();// 返回前一个页面X
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

	@Override
	protected void onPause() {
		super.onPause();
		if(URL.equals(SHOP)){
			MobclickAgent.onPageEnd("白送");

		}
		if(URL.equals(GIFT)){
			MobclickAgent.onPageEnd("新生大礼包");
		}
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if(URL.equals(SHOP)){
			MobclickAgent.onPageStart("白送");

		}
		if(URL.equals(GIFT)){
			MobclickAgent.onPageStart("新生大礼包");
		}
		MobclickAgent.onResume(this);
	}

	@Override
	public void finish() {
		Intent intent = new Intent(this,MainTabActivity.class);
		intent.putExtra(MainTabActivity.INDEX,MainTabActivity.TAG_INDEX);
		startActivity(intent);
	}
}
